<template>
  <div class="h-full flex flex-col">
    <page-header title="回收"> </page-header>
    <div class="mt-[16px]"></div>
    <n-card class="p-4 h-full" content-style="padding: 0">
      <n-grid x-gap="10" :cols="24">
        <!-- 操作台 -->
        <n-gi :span="14">
          <!-- 搜索 -->
          <div>
            <!-- <n-select /> -->
            <SearchProducts
              product-type="tradein"
              placeholder="搜索设备"
              v-model:value="searchKeyword"
              @pick="handlePickSearchProduct"
            />
          </div>
          <!-- 面包屑 -->
          <div class="mt-2"></div>
          <n-breadcrumb>
            <n-breadcrumb-item
              v-for="(breadCrumb, index) in breadCrumbs"
              :key="breadCrumb.key"
              @click.stop="handleClickBreanCrumb(breadCrumb, index)"
            >
              {{ breadCrumb.name }}
            </n-breadcrumb-item>
          </n-breadcrumb>
          <!-- STEPS -->
          <div class="mt-2"></div>
          <n-scrollbar :style="scrollContainerStyle">
            <!-- 选择分类 -->
            <ChooseCategory
              v-if="currentStep === TradeInStepEnum.CHOOSE_CATEGORY"
              @selected="handleSelectedCategory"
            />
            <!-- 选择品牌 -->
            <ChooseBrand
              v-else-if="currentStep === TradeInStepEnum.CHOOSE_BRAND"
              @selected="handleSelectedBrand"
            />
            <!-- 选择产品 -->
            <ChooseModel
              :category-id="tradeinForm.categoryId"
              :brand-id="tradeinForm.brandId"
              v-else-if="currentStep === TradeInStepEnum.CHOOSE_MODEL"
              @selected="handleSelectedProduct"
            />
            <!-- 选择SKU -->
            <ChooseGeneral
              :product-id="tradeinForm.productId"
              v-else-if="currentStep === TradeInStepEnum.CHOOSE_GENERAL"
              @selected="handleSelectedSku"
            />
            <!-- 选择问题 -->
            <ChooseQuestion
              :product-id="tradeinForm.productId"
              :variant="tradeinForm.variant"
              v-else-if="currentStep === TradeInStepEnum.CHOOSE_QUESTION"
              @selected="handleAddToCart"
            />
          </n-scrollbar>
        </n-gi>
        <!-- Cart -->
        <n-gi :span="10" class="flex flex-col flex-1">
          <div class="flex items-center">
            <n-select
              placeholder="请选择客户"
              :loading="customerSearchLoading"
              remote
              clearable
              filterable
              :options="customersList"
              value-field="id"
              label-field="name"
              @search="handleSearchCustomer"
              @update:value="handleChangeCurrentCustomer"
              v-model:value="currentCustomerId"
            >
            </n-select>
            <n-button
              quaternary
              circle
              class="ml-2"
              @click.stop="handleShowModal"
            >
              <template #icon>
                <n-icon><PersonAdd /></n-icon>
              </template>
            </n-button>
            <n-button quaternary circle class="ml-2">
              <template #icon>
                <n-icon><CreateOutline /></n-icon>
              </template>
            </n-button>
          </div>
          <div class="mt-2"></div>
          <n-scrollbar :style="scrollContainerStyle">
            <n-space vertical v-if="cartList.length">
              <div class="cart-item" v-for="item in cartList">
                <div class="flex basis-3/4">
                  <img class="w-[80px] h-[80px]" />
                  <div class="flex flex-col justify-between flex-1 pl-2">
                    <div>{{ item.productName }}</div>
                    <div>{{ item.variant.name }}</div>
                    <div>{{ item.imei }}</div>
                  </div>
                </div>
                <div class="flex flex-col justify-between text-right">
                  <n-space justify="end">
                    <n-button
                      size="tiny"
                      secondary
                      strong
                      type="info"
                      @click.stop="handleShowCartItem(item)"
                    >
                      <template #icon>
                        <n-icon><InformationCircle /></n-icon>
                      </template>
                    </n-button>
                    <n-button
                      size="tiny"
                      secondary
                      strong
                      type="error"
                      @click.stop="removeCartItem(item)"
                    >
                      <template #icon>
                        <n-icon><Trash /></n-icon>
                      </template>
                    </n-button>
                  </n-space>
                  <div>
                    <n-input-number
                      style="max-width: 200px"
                      v-model:value="item.customerPrice"
                    >
                      <template #prefix> {{ MONET_PREFIX }} </template>
                    </n-input-number>
                  </div>
                </div>
              </div>
            </n-space>

            <n-empty
              v-else
              class="mt-[30vh]"
              size="large"
              description="请选择设备"
            >
            </n-empty>
          </n-scrollbar>
          <div class="mt-2">
            <div class="mb-1 flex justify-between">
              <div>
                <n-button text :disabled="cartListIsEmpty"> 添加备注 </n-button>
              </div>
              <div>
                总成交价: <span>{{ currencyFormat(totalPrice) }}</span>
              </div>
            </div>
            <div class="flex justify-between">
              <n-button
                secondary
                @click.stop="discard"
                :disabled="cartListIsEmpty"
                >清空回收清单</n-button
              >
              <n-button
                type="primary"
                @click.stop="handleClickSubmit"
                :loading="confirmLoading"
                :disabled="confirmDisabled"
                >确认</n-button
              >
            </div>
          </div>
        </n-gi>
      </n-grid>
    </n-card>
    <!-- 新增客户弹窗 -->
    <CustomerModal
      title="新增客户"
      :action-type="actionType"
      v-model:show="modalShowFlag"
    />
    <!-- 选择支付方式弹窗 -->
    <PaymentModal
      title="选择支付方式"
      :confirm-loading="confirmLoading"
      v-model:show="showPayment"
      :payment-methods="paymentMethods"
      :total-price="totalPrice"
      @cancel="handleHidePayment"
      @close="handleHidePayment"
      @confirm="handleClickConfirm"
    />
    <CartItemDetail
      :title="cartItemDetailTitle"
      :cart-item="cartItemDetailObj"
      v-model:show="showCartItemDetail"
      @close="handleCloseCartItem"
      @cancel="handleCloseCartItem"
      @confirm="handleUpdateCartItem"
    />
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive, computed } from "vue";
import { useRouter } from "vue-router";
import { v4 as uuidv4 } from "uuid";
import { useDialog, useMessage } from "naive-ui";
import Big from "big.js";
import { cloneDeep, debounce, get } from "lodash-es";
import {
  InformationCircle,
  PersonAdd,
  CreateOutline,
  Trash,
} from "@vicons/ionicons5";
import * as RouterNames from "@/router/routerNames/index";
import { Category } from "@/types/model/product/vos/category.vo";
import { Brand } from "@/types/model/product/vos/brand.vo";
import { BreadCrumb, useBreadCrumbs } from "@/common/hooks/useBreadCrumbs";
import { TradeInStepEnum, BreadCrumbEnmu, TradeInForm } from "./data";
import { tradeinCheckout } from "@/api/tradein/tradein.api";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { Product } from "@/types/model/product/vos/product.vo";
import { SearchProductVO } from "@/types/model/product/vos/searchProducts.vo";
import CustomerModal from "@/components/biz/customerModal/index.vue";
import {
  useSearchCustomers,
  useCustomerModal,
} from "@/components/biz/customerModal/hooks";
import PaymentModal from "@/components/biz/paymentModal/index.vue";
import { usePaymentModal } from "@/components/biz/paymentModal/hooks";
import CartItemDetail from "@/components/biz/tradeInCartItem/index.vue";
import SearchProducts from "@/components/biz/searchProduct/index.vue";
import { DictStorage } from "@/storage/dict.storage";
import { MONET_PREFIX } from "@/constants/global";
import ChooseCategory from "./components/chooseCategory/index.vue";
import ChooseBrand from "./components/chooseBrand/index.vue";
import ChooseModel from "./components/chooseModel/index.vue";
import ChooseGeneral from "./components/chooseGeneral/index.vue";
import ChooseQuestion from "./components/chooseQuestion/index.vue";

const scrollContainerStyle = {
  flex: 1,
  minHeight: "calc(100vh - 278px)",
  maxHeight: "calc(100vh - 278px)",
};

const paymentMethods = DictStorage.getDictItemsByCode(
  "pos_tradein_payment_method"
);

const router = useRouter();
const dialog = useDialog();
const message = useMessage();

const { breadCrumbs, addBreadItem, updateBreadIItem, clearBreadCrumbs } =
  useBreadCrumbs();

const { actionType, modalShowFlag, handleShowModal } = useCustomerModal();

const { customersList, customerSearchLoading, handleSearchCustomer } =
  useSearchCustomers();

const {
  modalShowFlag: showPayment,
  handleShowModal: handleShowPaymentModal,
  handleHideModal: handleHidePaymentModal,
} = usePaymentModal();

const searchKeyword = ref<string>("");
const cartItemDetailTitle = ref<string>("");
const showCartItemDetail = ref<boolean>(false);
const cartItemDetailObj = ref<TradeInForm>({} as TradeInForm);

const currentStep = ref<TradeInStepEnum>(TradeInStepEnum.CHOOSE_CATEGORY);
const currentCustomerId = ref<string | undefined>(undefined);
const currentCustomerObj = ref<any>({});
const tradeinForm = reactive<TradeInForm>({
  uuid: "",
  categoryId: "",
  categoryName: "",
  brandId: "",
  brandName: "",
  productId: "",
  productName: "",
  imei: "",
  variant: {},
  checkList: {},
  selectedChcekMap: {},
  shownTradeinPrice: 0,
  customerPrice: 0,
});

const cartList = ref<TradeInForm[]>([]);
const confirmLoading = ref<boolean>(false);

const cartListIsEmpty = computed(() => {
  return cartList.value.length === 0;
});

const confirmDisabled = computed(() => {
  if (!currentCustomerId.value) {
    return true;
  }
  if (!cartList.value.length) {
    return true;
  }

  return false;
});

const totalPrice = computed(() => {
  let _total = new Big(0);
  cartList.value.forEach((item) => {
    _total = _total.plus(item.customerPrice);
  });

  return _total.toNumber();
});

const handleChangeCurrentCustomer = (_: any, opt: any) => {
  currentCustomerObj.value = cloneDeep(opt);
};

const init = () => {
  addBreadItem(BreadCrumbEnmu.CATEGORY, "选择分类", "");
};

/**
 * 点击面包屑回退
 */
const handleClickBreanCrumb = (_: BreadCrumb, index: number) => {
  breadCrumbs.value = breadCrumbs.value.slice(0, index + 1);
  breadCrumbs.value[index].name = breadCrumbs.value[index].initialName;
  breadCrumbs.value[index].value = breadCrumbs.value[index].initialValue;
  currentStep.value = breadCrumbs.value[index].key as any;
};

/**
 * 选中分类
 */
const handleSelectedCategory = (payload: Category) => {
  const categoryName = get(payload, "name") || "";
  const categoryId = get(payload, "id") || "";
  tradeinForm.categoryId = categoryId;
  tradeinForm.categoryName = categoryName;
  updateBreadIItem(BreadCrumbEnmu.CATEGORY, categoryName, categoryId);
  addBreadItem(BreadCrumbEnmu.BRAND, "选择品牌", "");
  currentStep.value = TradeInStepEnum.CHOOSE_BRAND;
};
/**
 * 选中品牌
 * @param payload
 */
const handleSelectedBrand = (payload: Brand) => {
  const brandName = get(payload, "name") || "";
  const brandId = get(payload, "id") || "";
  tradeinForm.brandId = brandId;
  tradeinForm.brandName = brandName;
  updateBreadIItem(BreadCrumbEnmu.BRAND, brandName, brandId);
  addBreadItem(BreadCrumbEnmu.MODEL, "选择产品", "");
  currentStep.value = TradeInStepEnum.CHOOSE_MODEL;
};

/**
 * 选中产品
 * @param Product payload
 */
const handleSelectedProduct = (payload: Product) => {
  const productName = get(payload, "name") || "";
  const productId = get(payload, "id") || "";
  tradeinForm.productId = productId;
  tradeinForm.productName = productName;
  updateBreadIItem(BreadCrumbEnmu.MODEL, productName, productId);
  addBreadItem(BreadCrumbEnmu.GENERAL, "选择规格", "");
  currentStep.value = TradeInStepEnum.CHOOSE_GENERAL;
};

/**
 * 选完SKU
 */
const handleSelectedSku = (payload: any) => {
  console.log(payload);
  const variantTitle = get(payload, "title") || "";
  tradeinForm.variant = cloneDeep(payload);
  updateBreadIItem(BreadCrumbEnmu.GENERAL, variantTitle, "");
  addBreadItem(BreadCrumbEnmu.QUESTION, "选择问题", "");
  currentStep.value = TradeInStepEnum.CHOOSE_QUESTION;
};

/**
 * 添加到购物车
 */
const handleAddToCart = (payload: any) => {
  tradeinForm.imei = payload.imei;
  tradeinForm.checkList = payload.checkList;
  tradeinForm.selectedChcekMap = payload.selectedChcekMap;
  tradeinForm.shownTradeinPrice = payload.shownTradeinPrice;
  tradeinForm.customerPrice = payload.shownTradeinPrice;
  tradeinForm.uuid = uuidv4();
  currentStep.value = TradeInStepEnum.CHOOSE_CATEGORY;

  cartList.value.push(cloneDeep(tradeinForm));

  resetTradeInForm();
  clearBreadCrumbs();
  addBreadItem(BreadCrumbEnmu.CATEGORY, "选择分类", "");
};

/**
 * 清空购物车
 */
const discard = () => {
  dialog.warning({
    title: "警告",
    content: "确定要清空回收清单吗？",
    positiveText: "确定",
    negativeText: "不确定",
    onPositiveClick: () => {
      cartList.value = [];
    },
  });
};

/**
 * 移除购物车项
 * @param cartItem
 */
const removeCartItem = (cartItem: TradeInForm) => {
  cartList.value = cartList.value.filter(
    (item: TradeInForm) => item.uuid !== cartItem.uuid
  );
};

const handleClickSubmit = debounce(async function () {
  if (!currentCustomerId.value) {
    dialog.warning({
      title: "温馨提示",
      content: "请选择客户",
      positiveText: "确定",
      negativeText: "取消",
    });
    return;
  }

  if (!cartList.value.length) {
    dialog.warning({
      title: "温馨提示",
      content: "回收清单为空，请添加回收设备",
      positiveText: "确定",
      negativeText: "取消",
    });
    return;
  }

  handleShowPaymentModal();
});

/**
 * 点击确认
 */
const handleClickConfirm = debounce(async function (paymentMethods: any[]) {
  confirmLoading.value = true;

  try {
    // if (!paymentMethods.length) {
    //   dialog.warning({
    //     title: "温馨提示",
    //     content: "请选择支付方式",
    //     positiveText: "确定",
    //     negativeText: "取消",
    //   });
    //   return;
    // }

    if (!currentCustomerId.value) {
      dialog.warning({
        title: "温馨提示",
        content: "请选择客户",
        positiveText: "确定",
        negativeText: "取消",
      });
      return;
    }

    if (cartList.value.length) {
      let _total = new Big(0);
      const params: any = {
        customerId: currentCustomerId.value,
        total: 0,
        items: [],
        payments: paymentMethods,
      };
      cartList.value.forEach((item: TradeInForm) => {
        const variantId = get(item, "variant.id") || "";
        const imei = get(item, "imei") || "";
        const originPrice = get(item, "shownTradeinPrice") || 0;
        const customPrice = get(item, "customerPrice") || 0;
        const selectedChcekMap = get(item, "selectedChcekMap") || {};
        const checkListId = get(item, "checkList.id") || "";
        _total = _total.plus(customPrice);
        let checkedQuestionIds: string[] = [];
        for (const key in selectedChcekMap) {
          if (selectedChcekMap[key] && selectedChcekMap[key] === "1") {
            checkedQuestionIds.push(key);
          }
        }
        params.items.push({
          variantId,
          checkListId,
          imei,
          originPrice,
          customPrice,
          checkedQuestionIds,
        });
      });

      params.total = _total;

      const resp = await tradeinCheckout(params);
      const orderId = get(resp, "result") || "";
      const resultMsg = get(resp, "message") || "添加成功";
      if (orderId) {
        message.success(resultMsg);
        router.push({
          name: RouterNames.TRADEIN_ORDER_DETAIL_PAGE.NAME,
          params: { id: orderId },
        });
      }
    }
  } finally {
    confirmLoading.value = false;
  }
}, 200);

const handleHidePayment = () => {
  if (!confirmLoading.value) {
    handleHidePaymentModal();
  }
};

const handleShowCartItem = debounce(function (payload) {
  cartItemDetailObj.value = cloneDeep(payload);
  cartItemDetailTitle.value = payload.variant.name;
  showCartItemDetail.value = true;
});

const handleCloseCartItem = () => {
  showCartItemDetail.value = false;
  cartItemDetailObj.value = {} as TradeInForm;
  cartItemDetailTitle.value = "";
};

const handleUpdateCartItem = (payload: TradeInForm) => {
  const uuid = get(payload, "uuid");
  if (uuid) {
    const targetIndex = cartList.value.findIndex(
      (item: TradeInForm) => item.uuid === uuid
    );
    console.log();
    if (targetIndex >= 0) {
      cartList.value[targetIndex] = cloneDeep(payload);
    }
  }
  handleCloseCartItem();
};

const resetTradeInForm = () => {
  tradeinForm.uuid = "";
  tradeinForm.categoryId = "";
  tradeinForm.categoryName = "";
  tradeinForm.brandId = "";
  tradeinForm.brandName = "";
  tradeinForm.productId = "";
  tradeinForm.productName = "";
  tradeinForm.imei = "";
  tradeinForm.variant = {};
  tradeinForm.checkList = {};
  tradeinForm.selectedChcekMap = {};
  tradeinForm.shownTradeinPrice = 0;
};

const handlePickSearchProduct = (searchProduct: SearchProductVO) => {
  const { categoryId, categoryName, brandId, brandName, id, name } =
    searchProduct;
  // 1. 清空面包屑
  clearBreadCrumbs();
  // 2. 重建面包屑
  addBreadItem(BreadCrumbEnmu.CATEGORY, "选择分类", "");
  updateBreadIItem(BreadCrumbEnmu.CATEGORY, categoryName, categoryId);
  addBreadItem(BreadCrumbEnmu.BRAND, "选择品牌", "");
  updateBreadIItem(BreadCrumbEnmu.BRAND, brandName, brandId);
  addBreadItem(BreadCrumbEnmu.MODEL, "选择产品", "");
  updateBreadIItem(BreadCrumbEnmu.MODEL, name, id);
  addBreadItem(BreadCrumbEnmu.GENERAL, "选择规格", "");
  // 3. 清空tradeinForm
  resetTradeInForm();
  tradeinForm.categoryId = categoryId;
  tradeinForm.categoryName = categoryName;
  tradeinForm.brandId = brandId;
  tradeinForm.brandName = brandName;
  tradeinForm.productId = id;
  tradeinForm.productName = name;
  currentStep.value = TradeInStepEnum.CHOOSE_GENERAL;
};

onMounted(() => {
  init();
});
</script>
<style lang="scss">
@import "./index.scss";
</style>
